import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/bean/show_files_bean.dart';
import 'package:flutter_ahj_app/base/utils/HttpNoTokenUtils.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/base/utils/oss/OSSUrlConsts.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerPage extends StatefulWidget {
  const VideoPlayerPage(
      {Key key, this.videoPath, this.videoSource, this.isLooping = false})
      : super(key: key);

  /// 视频来源
  final String videoSource;

  /// 视频路径
  final String videoPath;

  /// 是否 循环
  final bool isLooping;

  @override
  _VideoPlayerPageState createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;
  String _filePath;

  @override
  void initState() {
    super.initState();

    //  OrientationPlugin.forceOrientation(DeviceOrientation.landscapeRight);
    setState(() {
      if (widget.videoPath != null) {
        if (widget.videoPath.startsWith("http")) {
          _filePath = widget.videoPath;
          _controller = VideoPlayerController.network(_filePath);
          _initializeVideoPlayerFuture = _controller.initialize();
          _controller.setLooping(widget.isLooping);
        } else if (widget.videoPath.startsWith("public")) {
          _filePath =
              OSSUrlConsts.URL_UPLOAD_IMAGE_OSS + "/" + widget.videoPath;
          _controller = VideoPlayerController.network(_filePath);
          _initializeVideoPlayerFuture = _controller.initialize();
          _controller.setLooping(widget.isLooping);
        } else if (File(widget.videoPath).existsSync()) {
          // Future.delayed(Duration.zero, () {
          //   _getImagePath();
          // });
          _filePath = widget.videoPath;
          _controller = VideoPlayerController.file(File(widget.videoPath));
          _initializeVideoPlayerFuture = _controller.initialize();
          _controller.setLooping(widget.isLooping);
        }
        // print("image:" + widget.fileName);
      }
    });

    // switch (widget.videoSource) {
    //   case "0":
    //     _controller = VideoPlayerController.asset(widget.videoPath);

    //     break;
    //   case "1":
    //     if (!widget.videoPath.startsWith("http")) {
    //       //短路径
    //       _getFilePath();
    //     } else {
    //       _controller = VideoPlayerController.network(widget.videoPath);
    //     }
    //     break;
    //   case "2":
    //     _controller = VideoPlayerController.file(File(widget.videoPath));
    //     break;

    //   default:
    // }

    if (DataSourceType.network == widget.videoSource &&
        !widget.videoPath.startsWith("http")) {
      return;
    }
  }

  ///获得图片路径
  _getImagePath() async {
    var params = {"a": "a"};

    ///fileName  文件名
    /// type  是否是视频1:是 0:不是
    String url = HttpBaseConst.serverUrl +
        HttpBaseConst.downloadPath +
        "?" +
        "fileName=" +
        widget.videoPath +
        "&type=1";
    HttpNoTokenUtils.httpGet(url, params, (result) {
      print(result);

      ShowFilesBean showFilesBean = ShowFilesBean.fromJson(json.decode(result));

      print("我是fileUrl" + showFilesBean.data.fileUrl);

      setState(() {
        _filePath = showFilesBean.data.fileUrl;
        _controller = VideoPlayerController.network(_filePath);
        _initializeVideoPlayerFuture = _controller.initialize();
        _controller.setLooping(widget.isLooping);
      });
    }, context: context);
  }

  ///获得长路径
  _getFilePath() async {
    var params = {"a": "a"};

    HttpUtils.httpGetImagePath(widget.videoPath, params, (data) {
      ShowFilesBean showFilesBean = ShowFilesBean.fromJson(json.decode(data));

      var _filePath = showFilesBean.data?.fileUrl;
      _controller = VideoPlayerController.network(_filePath)..initialize();
      _initializeVideoPlayerFuture = _controller.initialize();
      _controller.setLooping(widget.isLooping);
    });

    ///fileName  文件名
    /// type  是否是视频1:是 0:不是
    // String url = HttpHidderConst.serverUrl + HttpHidderConst.downloadPath + "?" + "fileName=" + urls + "&type=0";
    // HttpUtils.httpGet(url, params, (result){
    //   print(result);
    //
    //   ShowFilesBean showFilesBean = ShowFilesBean.fromJson(json.decode(result));
    //
    //   print("我是fileUrl" +  showFilesBean.data.fileUrl);
    //
    //   setState(() {
    //
    //     _filePath = showFilesBean.data.fileUrl+urls;
    //     _videoUrl = showFilesBean.data.fileUrl+urls;
    //     _controller = VideoPlayerController.network(
    //         _filePath)
    //       ..initialize();
    //   });
    // }, context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('视频播放'),
      ),
      body: FutureBuilder(
        future: _initializeVideoPlayerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Center(
              child: Stack(
                children: [
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _controller.value.isPlaying
                            ? _controller.pause()
                            : _controller.play();
                      });
                    },
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        _controller.value.isPlaying
                            ? _controller.pause()
                            : _controller.play();
                      });
                    },
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: Offstage(
                        offstage: _controller.value.isPlaying,
                        child: Container(
                          color: Colors.black.withOpacity(0.3),
                          child: Icon(
                            _controller.value.isPlaying
                                ? Icons.pause
                                : Icons.play_arrow,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: () {
      //     setState(() {
      //       _controller.value.isPlaying
      //           ? _controller.pause()
      //           : _controller.play();
      //     });
      //   },
      //   child: Icon(
      //     _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
      //   ),
      // ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
}
